Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

Solution:

  1. public class Solution {
  2. public int romanToInt(String s) {
  3. // Roman to Int map
  4. Map<Character, Integer> map = new HashMap<>();
  5. map.put('I', 1);
  6. map.put('V', 5);
  7. map.put('X', 10);
  8. map.put('L', 50);
  9. map.put('C', 100);
  10. map.put('D', 500);
  11. map.put('M', 1000);
  12. int n = s.length();
  13. int i = n - 1;
  14. int sum = map.get(s.charAt(i--));
  15. while (i >= 0) {
  16. int curr = map.get(s.charAt(i));
  17. int next = map.get(s.charAt(i + 1));
  18. if (curr >= next) {
  19. sum += curr;
  20. } else {
  21. sum -= curr;
  22. }
  23. i--;
  24. }
  25. return sum;
  26. }
  27. }